import express from 'express';
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
const app = express();
const port = 3000;
app.use(express.json());
//查询
app.get('/findMany', async (req, res) => {
    const users = await prisma.user.findMany({
        include:{posts:true}
    });
    res.send(users);
});

//通过id查询
app.get('/findOne/:id', async (req, res) => {
    const { id } = req.params;
    const user = await prisma.user.findMany({
        where: { id: Number(id) },
        include:{posts:true}
    });
    res.send(user);
});

//添加
app.post('/add', async (req, res) => {
    const { name, email,password } = req.body;
    //创建用户
    const data=await prisma.user.create({
       data:{
         name,email,password,
         posts:{
            create:[
                {title:'文章1',content:'文章1内容'},
                {title:'文章2',content:'文章2内容'},
             ]
         }
       }
    })
    res.send(data)
}) 

//编辑
app.post('/update', async (req, res) => {
    const { name, email,id } = req.body;
    const data=await prisma.user.update({
        where: { id: Number(id) },
        data: { name, email },
    });
    res.send(data);
}) 

//删除
app.post('/delete', async (req, res) => {
    const { id } = req.body;
    await prisma.post.deleteMany({
        where: { authorId: Number(id) },
    });
    const data=await prisma.user.delete({
        where: { id: Number(id) },
    });
    res.send(data);
}) 

app.listen(port, () => {
  console.log('Server is running on port 3000');
});